import React from 'react'
import moment from 'moment'
import config from 'config'
import {messages, deepCopy, deepFullCopy, bankAccountNoEncryption, queryCurrencyPrecision} from 'share/common'
import {Alert, Switch, Input, Select, Row, Col, InputNumber, DatePicker, Table, Popover, TimePicker, Tooltip, message} from 'antd'

const {TextArea} = Input;
const Option = Select.Option;
const { RangePicker, MonthPicker } = DatePicker;
import 'styles/custom-fields.scss'
import constants from 'share/constants'
import Chooser from 'components/chooser'
import Selector from 'components/selector'
import IsVenMaster from 'components/template/combination-custom-form/is-ven-master'
import chooserData from 'share/chooserData'
import configureStore from 'stores'
import ImageUpload from 'components/image-upload'
import Searcher from 'components/searcher'
import AddTableCell from 'components/template/add-table-cell'
import ExpenseTypeModal from 'containers/request/new-request/expense-type-modal'
import ExpenseTypeFrame from 'containers/request/new-request/expense-type-frame'
import NewVenMaster from 'containers/request/new-request/new-ven-master'
import NewDestination from 'containers/request/new-request/new-destination'
import NewLinkageSwitch from 'containers/request/new-request/new-linkage-switch'
import NewPayee from 'containers/request/new-request/new-payee'
import ExpenseAllocateForm from 'containers/request/travel-request/expense-allocate-form';
import SelectDateForm from 'containers/request/travel-request/select-date-form';
import ExternalParticipantName from 'containers/request/custom-field/external-participant-name'
import SelectParticipantDetail from 'containers/expense-report/template/select-participant-detail'
import {Modal, Icon} from "antd/lib/index";
import FileUpload from 'components/file-upload'
import IeFileUpload from 'components/template/ie-file-upload/ie-file-upload'
import IeImgUpload from 'components/template/ie-file-upload/ie-img-upload'
import Condition from 'components/condition'
import TravelLocation from 'containers/request/travel-request/comp/location'
import UnifiedTable from 'components/template/widget/unified-table/UnifiedTable'
import SwitchWrapper from 'components/template/widget/switch-wrapper/SwitchWrapper'
import { formatNumber  } from "share/common";

const { If, Else } = Condition;

function omit(obj, key) {
  return Object.keys(obj).reduce((left, right) => {
    if (right !== key) {
      left[right] = obj[right];
    }
    return left;
  }, {});
}

export default {
  /**
   * @description
   * @param fields 表单渲染项
   * @param info 数据源信息 eg 报销单信息
   * @param applicant 申请人信息
   * @param pageFrom 页面来源
   * @param signName 自选审批人fieldName
   * */
  renderFields(fields, info, applicant, pageFrom, signName) {
    let showFields = deepCopy(fields);
    let rows = [];
    let cols = [];
    let renderImageList = [];
    let renderTableList = [];
    const {formCode} = info;
    //加签人,非自定义表单
    if (info.countersignApproverNames) {
      let countersignApproverNames = [];
      info.countersignApproverNames.map(item => {
        countersignApproverNames.push(item.fullName);
      })
      showFields.push({
        fieldName: signName ? signName : messages('components.key376'/*自选审批人*/),
        formValueOID: 'addSign',//这个只是不让cols里的key不为null，没有实际使用逻辑
        messageKey: "addSign",
        showValue: countersignApproverNames.join(',')
      })
    }
    let filterMoney = React.Component.prototype.filterMoney;
    showFields.map(item => {
      if (item.messageKey === 'average_budget') {
        item.renderValue = item.showValue ? `${info.currencyCode} ${filterMoney(item.showValue,queryCurrencyPrecision(info.currencyCode),true)}` : `${info.currencyCode} 0.00`
      }
      if (item.messageKey === 'total_budget') {
        if (info.formType != 2005) {
          item.renderValue = item.showValue ? `${info.currencyCode} ${filterMoney(item.showValue,queryCurrencyPrecision(info.currencyCode),true)}` : `${info.currencyCode} 0.00`
        } else {
          item.renderValue = item.showValue ? `${filterMoney(item.showValue,queryCurrencyPrecision(info.originCurrencyCode),true)}` : `0.00`
        }
      }
      if (item.messageKey === 'start_date' || item.messageKey === 'end_date') {
        let fieldConstraint = item.fieldConstraint ? JSON.parse(item.fieldConstraint) : {};
        if (fieldConstraint.enableTime) {
          item.renderValue = item.showValue ? moment(item.showValue).format('YYYY-MM-DD HH:mm') : '-';
        } else {
          item.renderValue = item.showValue ? moment(item.showValue).format('YYYY-MM-DD') : '-';
        }
      }
      if (item.messageKey === 'select_department' || item.messageKey === 'select_cost_center') {
        let fieldConstraint = item.fieldConstraint ? JSON.parse(item.fieldConstraint) : {};
        let {showValue, valueCode} = item;
        if (showValue) {
          if (item.messageKey === 'select_department' && React.Component.prototype.checkFunctionProfiles('department.full.path.disabled', [true])) {
            showValue = showValue.split("|").pop();
          }
          item.renderValue = (
            <span>
              {showValue}
              {fieldConstraint.withCode && valueCode && (
                <span style={{fontSize: 12, color: '#989898'}}>({valueCode})</span>
              )}
            </span>
          )
        }
      }
      if (item.messageKey === 'common.date' || item.messageKey === 'date') {
        if (item.fieldCode === 'ExpenseYM') {
          item.renderValue = item.showValue ? moment(item.showValue).format('YYYY-MM') : '-'
        } else {
          item.renderValue = item.showValue ? moment(item.showValue).format('YYYY-MM-DD') : '-'
        }
      }
      if (item.messageKey === 'dateTime') {
        item.renderValue = item.showValue ? moment(item.showValue).format('YYYY-MM-DD HH:mm') : '-'
      }
      if (item.messageKey === 'contact_bank_account') {
        this.dealSpecialFormShow(cols, item, info);
      }
      if (item.messageKey === 'time') {
        item.renderValue = item.showValue ?
          (moment(item.showValue)['_isValid'] ? moment(item.showValue).format('HH:mm') : item.showValue) : '-'
      }
      if (item.messageKey === 'linkage_switch') {
        if (item.showValue === 'true') {
          item.renderValue = (
            <div>
              {JSON.parse(item.fieldContent || '[]').map(item => (
                <div key={item.id}>
                  {item.fieldName ? `${item.fieldName}：` : ''}{item.name || item.value || '-'}
                </div>
              ))}
            </div>
          )
        } else {
          item.renderValue = messages('components.key377'/*否*/)
        }
      }
      if (item.messageKey === 'venMasterSwitch') {
        if (item.value === 'true') {
          this.dealSpecialFormShow(cols, item, info, 'venMaster');
          let fieldContent = item.fieldContent ? JSON.parse(item.fieldContent) : {};
          let value;
          let name;
          fieldContent.map(item => {
            if (item.messageKey === 'venMaster') {
              name = item.fieldName
              value = item.value
            }
          })
          item.renderValue = <NewVenMaster value={value} onlyShow={true}/>;
          cols.push(
            <Col span={8} key={item.formValueOID} className="field-container">
              <div className="field-name">{item.fieldName}</div>
              <div
                className="field-content">{item.value === 'true' ? messages('common.yes') : messages('common.no')}</div>
            </Col>
          )
          cols.push(
            <Col span={8} className="field-container">
              <div className="field-name">{name}</div>
              <div className="field-content">{item.renderValue || '-'}</div>
            </Col>
          )
        } else {
          this.dealSpecialFormShow(cols, item, info, 'contact_bank_account');
        }
      }
      if (item.messageKey === 'switch' || item.messageKey === 'writeoff_flag') {
        item.renderValue = item.showValue === 'true' ? messages('components.key378'/*是*/) : messages('components.key377'/*否*/)
      }
      if (item.messageKey === 'select_box' || item.messageKey === 'more_cust_list' || item.messageKey === 'city') {
        let value = [];
        let key = item.messageKey === 'city' ? 'city' : 'name';
        try {
          JSON.parse(item.showValue || '[]').map(item => {
            value.push(item[key]);
          });
          item.renderValue = value.join(',') || '-';
        } catch(e) {
          item.renderValue = item.showValue || '-';
        }
      }
      if (item.messageKey === 'select_participant') {
        if(config.formCodes.indexOf(info.formCode) > -1) return;
        let isUse = true;
        if (item.fieldContent) {
          let temp = JSON.parse(item.fieldContent);
          isUse = temp.isUse;
        }
        if (!isUse) {
          return;
        }
        let value = [];
        let title = deepFullCopy(item.fieldName);
        //需求3768 报销单关联申请单时带入范围以外的参与人需要标记出来
        let firstName;
        let valLen;
        if (info.expenseReportOID) {
          let showValue = JSON.parse(item.showValue || '[]').sort((a, b) => Number(b.highOff || null) - Number(a.highOff || null));
          valLen = showValue.length;
          showValue.map((item, index) => {
            const {fullName} = item;
            if(index === 0) {
              firstName = fullName;
            }
            value.push(`<span style="color: ${item.highOff ? '#000000a6' : '#fe9a07'}">${fullName}</span>`)
          });
          item.showValue = valLen ? (<div>
            <div>{messages(`mcd.${valLen === 1 ? 'one' : 'more'}.person`, {arg1: firstName, arg2: valLen})}</div>
            <div className="names">{value.join(',') || '-'}</div>
          </div>) : <div> - </div>;
        } else {
          JSON.parse(item.showValue || '[]').map((item, index) => {
            const {fullName} = item;
            value.push(fullName)
            if(index === 0) {
              firstName = fullName;
            }
          });
          valLen = value.length;
          item.renderValue = valLen ? (<div>
            <div>{messages(`mcd.${valLen === 1 ? 'one' : 'more'}.person`, {arg1: firstName, arg2: valLen})}</div>
            <div className="names">{value.join(',') || '-'}</div>
          </div>) : <div> - </div>;
        }
        //需求4002 参与人控件可查看详情（仅审核-查看报销单详情界面）
        if (pageFrom === 'auditView') {
          item.fieldName = <SelectParticipantDetail field={item} title={title}/>
        }
      }
      if(item.messageKey === 'external_participant_name' || item.messageKey === 'out_participant_name') { //外部乘机人
        item.renderValue = JSON.parse(item.showValue || '[]').length ? (
          <ExternalParticipantName field={item} value={JSON.parse(item.showValue || '[]')}/>
        ) : '-';
      }
      if (item.messageKey === 'employee_expand') {
        if ((item.attachmentImages || []).length) {
          if (window.ISIE9) {
            item.renderValue = (
              <IeImgUpload defaultFileList={item.attachmentImages} disabled/>
            )
          } else {
            item.renderValue = (
              <ImageUpload defaultFileList={item.attachmentImages}
                           attachmentType="INVOICE_IMAGES"
                           disabled/>
            );
          }
          renderImageList.push(item)
        }
      }
      if (item.messageKey === 'attachment' || item.messageKey === 'image') { //附件 图片
        item.renderValue = (item.attachmentImages || []).length ? (
          <Condition>
            <If value={window.ISIE9}>
              <IeFileUpload defaultFileList={item.attachmentImages} disabled/>
            </If>
            <Else>
              <FileUpload defaultFileList={item.attachmentImages}
                          attachmentType="INVOICE_IMAGES"
                          showFileName={true}
                          isShowDefault
                          disabled/>
            </Else>
          </Condition>
        ) : '-';
        renderImageList.push(item)
      }
      //差旅单编辑状态下预算明细控件不在renderField里渲染
      //从关闭列表页进来的单据详情页，不在此处处理预算明细
      // if (item.messageKey === 'budget_detail' && !(info.status === 1001 && info.formType === 2001) && pageFrom !== 'closeList') { //预算明细
      //   renderTableList.push(<ExpenseTypeFrame field={item} info={info}/>)
      // }
      if (item.messageKey === 'exp_allocate') { //费用分摊
        let columns = [];
        let data = [];
        JSON.parse(item.showValue || '[]').map((record, i) => {
          let record_data = {
            id: i,
            scale: record.scale
          };
          record.costCenterItems.map((item, index) => {
            i === 0 && columns.push({title: item.fieldName, dataIndex: `data_${index}`, render: value => value || '-'});
            record_data[`data_${index}`] = item.name
          });
          data.push(record_data)
        });
        columns.push({title: messages('components.key386'/*分摊比例(%)*/), dataIndex: 'scale'});
        item.value && renderTableList.push(<Table rowKey="id"
                                                  columns={columns}
                                                  dataSource={data}
                                                  pagination={false}
                                                  bordered
                                                  size="middle"/>)
      }
      if (item.messageKey === 'venMaster') {
        item.renderValue = <NewVenMaster value={item.value} onlyShow={true}/>
      }
      if (item.messageKey === 'cust_list') {
        let list = []
        if (!['SQ', 'BX', 'JK'].includes(item.fieldCode)) {
          if (item.fieldCode === "carIID") {
            // console.log("item", item.value)
            item.value && JSON.parse(item.value).map(e => {
              list.push(e.carNumber)
            })
            // console.log('list', list)
            item.renderValue = list.join() || '-';
          } else {
            item.renderValue = item.showValue || '-'
          }
        } else {
          item.value && JSON.parse(item.value).map(e => {
            list.push(e.formName)
          })
          item.renderValue = list.join() || '-';
        }
      }
      let showDifferentMapping = {
        select_department: 'departmentOID',
        select_company: 'companyOID'
      }
      if (item.messageKey === 'input' && (item.fieldName === '默认额度' || item.fieldName === '当前额度' || item.fieldName === '政策规定额度' || item.fieldName === '申请额度')) {
        item.renderValue = formatNumber(item.value) || '-'
      }

      if (item.fieldCode === 'quota' && item.fieldName === '申请额度') {
        item.renderValue = formatNumber(item.value) || '-'
      }

      //处理线下机票单据的行程数据，用来做特殊行程展示
      let hideFieldForZxOffline = false;
      let { fieldCode } = item;
      if (formCode === 'OFFLINE_FLIGHT_CONFIRMATION_FORM' &&
        (fieldCode === 'going' || fieldCode === 'applicationType' || fieldCode === 'excessiveMatters' || fieldCode === 'excessiveReason' ||
          fieldCode === 'overstepBufferReason' || fieldCode === 'approvalType' || fieldCode === 'orderType' || fieldCode === 'orderNo' ||
          fieldCode === 'supplierOrder' || fieldCode === 'travelNo')) {
        hideFieldForZxOffline = true;
      }
      //处理线下酒店单据的行程数据，用来做特殊行程展示
      if (formCode === 'OFFLINE_HOTEL_CONFIRMATION_FORM' &&
        (fieldCode === 'HOTEL_NAME' || fieldCode === 'STAR' || fieldCode === 'FROM_DATE' ||
        fieldCode === 'LEAVE_DATE' || fieldCode === 'passenger' || fieldCode === 'HOTEL_STAYS' ||
        fieldCode === 'ROOM_TYPE' || fieldCode === 'ROOM_NUMBER' || fieldCode === 'HOTEL_UNIT_PRICE' ||
        fieldCode === 'BOOKING_RULES' || fieldCode === 'approvalType' || fieldCode === 'orderType' ||
          fieldCode === 'orderNo' || fieldCode === 'supplierOrder' || fieldCode === 'travelNo')) {
        hideFieldForZxOffline = true;
      }

      // 申请人部门与详情部门不一致 显示需要高亮
      if (['budget_detail', 'exp_allocate', 'attachment', 'image', 'contact_bank_account', 'venMasterSwitch', 'prompt_key','public.assembly'].indexOf(item.messageKey) === -1 &&
        !(item.attachmentImages && item.attachmentImages.length) && !hideFieldForZxOffline) {
        let showText = item.renderValue || item.showValue || '-';
        let filedName = ['maxnum', 'department', 'costcenter'].indexOf(item.fieldCode) < 0 ? item.fieldName : (
          <span>
            {item.fieldName}&nbsp;
            <Tooltip title={messages(`mcd.tip.${item.fieldCode}`/*根据公司政策规定，有其他雇员一起出差，同性雇员在可能情况下须合住双人标准房间。*/)}>
              <Icon type="question-circle-o" style={{color: '#4E5B71'}} />
            </Tooltip>
          </span>
        );
        cols.push(
          <Col span={8} key={item.formValueOID} className="field-container 1">
            <div className="field-name">{filedName}</div>
            <div className="field-content"
                 style={(
                   applicant &&
                   ~Object.keys(showDifferentMapping).indexOf(item.messageKey) &&
                   applicant[showDifferentMapping[item.messageKey]] &&
                   item.value !== applicant[showDifferentMapping[item.messageKey]]
                 ) ? {color: '#f50'} : {}}>
              {!!item.renderValue ? showText : (
                <span style={{whiteSpace: 'pre-wrap'}} dangerouslySetInnerHTML={{__html: showText}}></span>
              )}
            </div>
          </Col>
        )
      }
    });
    if (formCode && formCode === 'SQ017') {
      cols.push(
        <Col span={8} className="field-container">
          <div className="field-name">账本及消费</div>
          <div className="field-content">我的账本，滴滴消费记录，公务卡消费</div>
        </Col>
      )
      cols.push(
        <Col span={8} className="field-container">
          <div className="field-name">还款单</div>
          <div className="field-content">还款单</div>
        </Col>
      )
    }
    let lineNum = Math.ceil(cols.length / 3);
    for(let i = 1; i <= lineNum; i++){
      let tempCol = [];
      if(i === lineNum){
        tempCol = cols.slice((i - 1) * 3);
      }else{
        tempCol = cols.slice((i - 1) * 3,i * 3);
      }
      rows.push(
        <Row type="flex" key={i} className={`custom-form-row ${window.ISIE9 ? 'custom-form-row-ie9' : ''}`}>
          {tempCol}
        </Row>
      );
    }
    //图片在最下方一行显示
    renderImageList.map((item, index) => {
      rows.push(
        <Row key={index + 1000} className="custom-form-row">
          <div className="field-name">{item.fieldName}</div>
          <div className="field-content">{item.renderValue || '-'}</div>
        </Row>
      )
    });
    //表格显示
    renderTableList.map((item, index) => {
      rows.push(<Row key={index + 2000} className="custom-form-row">{item}</Row>)
    });
    return rows;
  },
  //处理特别的控件显示
  dealSpecialFormShow(cols, item, info, messageKey = item.messageKey) {
    if (messageKey === 'contact_bank_account') {
      let isExpenseReport = info.expenseReportOID;
      let showValue = item.showValue && isExpenseReport ? JSON.parse(item.showValue) : isExpenseReport ? {} : {bankAccountNo: item.showValue};
      if (item.messageKey === 'venMasterSwitch' && !isExpenseReport) {
        showValue = JSON.parse(item.showValue);
      }
      let otherFields = [];
      if (item.messageKey === 'venMasterSwitch') {
        let fieldContent = item.fieldContent ? JSON.parse(item.fieldContent) : {};
        otherFields.push({
          fieldName: item.fieldName,
          renderValue: item.value === 'true' ? messages('common.yes') : messages('common.no')
        });
        let fieldName;
        fieldContent.map(item => {
          if (item.messageKey === 'contact_bank_account') {
            fieldName = item.fieldName;
            showValue = item.showValue && isExpenseReport ? JSON.parse(item.showValue) : isExpenseReport ? {} : {bankAccountNo: item.showValue};
          }
        })
        otherFields.push({
          fieldName: fieldName,
          renderValue: showValue.bankAccountNo
        });
      }
      else {
        item.renderValue = showValue.bankAccountNo;
        otherFields.push({
          fieldName: item.fieldName,
          renderValue: showValue.bankAccountNo
        });
      }

      if (isExpenseReport) {
        otherFields.push({
          fieldName: messages('components.key387'/*开户支行*/),
          renderValue: showValue.branchName
        });
        otherFields.push({fieldName: messages('components.key388'/*联行号*/), renderValue: showValue.bankCode});
        otherFields.push({
          fieldName: messages('components.key389'/*开户名*/),
          renderValue: showValue.bankAccountName
        });
      }
      item.renderValue = (
        <div>
          {otherFields.map((i, index) => {
            cols.push(
              <Col span={8} key={`${item.formValueOID}${index}`} className="field-container">
                <div className="field-name">{i.fieldName}</div>
                <div className="field-content">{i.renderValue || '-'}</div>
              </Col>)
          })}
        </div>
      )
    }
  },
  /**
   * @description form表单项渲染
   * @param field Field 表单项内容
   * @param fieldDefaultValue FieldDefaultValue 表单项默认值
   * @param customFormFields CustomFormFields 部分控件需要用到表单信息 例如 收款单位 (去除 formDetail中含有该对象)
   * @param formDetail FormDetail 数据源对象
   * @param copyValue
   * @param formValues 表单值
   * @param type Number 1:等于申请单 2：报销单 3: 借款单
   * @param getPopupContainer 滚动元素相对元素对象
   * @param jobId 单据岗位id
   * @param jobInfo 单据岗位的岗位信息
   * @param isSwitchChecked “是否显示联动按钮”是否打开,
   * @param onSwitchChange “是否显示联动按钮”发生变化时的回调事件
   * @param onAgentChange “是否打开代理”发生变化时的回调事件
   * @param onApproverChange “是否打开代理”发生变化时的回调事件
   * @param onProxy “代理”发生变化时的回调事件
   * @param onCompanyChange 礼品申请单费用承担公司发生变化时的回调事件
   * @param onDepartmentChange 礼品申请单费用承担部门发生变化时的回调事件
   * */
  renderForm({
    field,
    fieldDefaultValue,
    copyValue,
    type = 1,
    formDetail = {},
    formValues = {},
    getPopupContainer = () => document.body,
    propsParams = {},
    jobId,
    jobInfo = {},
    onSwitchChange,
    onAgentChange,
    onApproverChange,
    onProxy,
    onCompanyChange,
    onDepartmentChange,
    applicantOID = null,
    isCustListSwitch,
    custListParams,
    additionalDefault,
    userIsHr,
    thirdUserEid,
    excleType,
    changeCompanyAndDepart,
    hrInfo
  }) {
    let chooserItem;
    const { departmentOID ,companyOID } = jobInfo;
    const { formCode } = formDetail;
    switch (field.messageKey) {
      case 'public.assembly':
        return (
          <SwitchWrapper
            isHidden={field.isHidden}
            switchText={field.switchText}
            isSwitchChecked={field.isSwitchOn}
            onSwitchChange={onSwitchChange}
            fieldInfo={field}
          >
            <UnifiedTable
              pkId={propsParams.pkId}
              formDataId={propsParams.formDataId}
              user={hrInfo}
              excleType={excleType}
              {...omit(field, 'value')}
            />
          </SwitchWrapper>
        );
      case 'prompt_key':
        return <div style={{lineHeight: '20px'}}>{field.promptInfo}</div>;
      case 'title':
        let disabledFlag = false
        if (formDetail.formCode === 'SQ021') {
          disabledFlag = true
        }
        return <TextArea rows={4} placeholder={field.promptInfo} style={{resize: 'none'}} disabled={disabledFlag}/>;
      case 'select_department':
        let companyOIDSetInDep = null;
        let companyValueList = this.byMkGetValue(formDetail.customFormFields, 'select_company', formValues);
        if (companyValueList && companyValueList.length > 0 && companyValueList[0]) {
          companyOIDSetInDep = typeof companyValueList[0] === 'object' ? companyValueList[0].key : companyValueList[0];
        } else {
          // 获取部门的默认公司应该是申请人的默认公司，而非当前公司模式下所属的公司 bug38377
          // 公司控件没有值时，取的应该是岗位所在公司
          companyOIDSetInDep = jobInfo.companyOID;
        }
        chooserItem = deepFullCopy(chooserData['department']);
        let leafEnable = !React.Component.prototype.checkFunctionProfiles('department.leaf.selection.required', [undefined, false]);
        chooserItem.columns.some(item => {
          if (item.dataIndex === 'name') {
            item.render = (value, record) => {
              let user = configureStore.store.getState().login.user;
              let message = '';
              if ((!departmentOID && user.departmentOID === record.departmentOid) || (departmentOID && departmentOID === record.departmentOid)) {
                message = messages('components.key696')/*(我的)*/;
              }
              return (
                <Popover
                  placement="topLeft"
                  overlayStyle={{ maxWidth: 500 }}
                  content={`${message}${record.path}`}>
                  {message}{React.Component.prototype.checkFunctionProfiles('department.full.path.disabled', [undefined, false]) ? record.path : record.name}
                </Popover>
              );
            };
          }
        });
        chooserItem.url += `?leafEnable=${leafEnable}`;
        if (formCode === 'BX006') { // 代提报销单
           // 代司机报销，表单信息用的是司机的上司，不是当前登录人，但是提交的时候申请人是当前登录人（秘书）
          chooserItem.url = chooserItem.url.indexOf('?') > -1 ? chooserItem.url + `&userOID=${applicantOID}` : chooserItem.url + `?userOID=${applicantOID}`
        }
        return (
          <Chooser
            selectorItem={chooserItem}
            valueKey="departmentOid"
            placeholder={field.promptInfo}
            labelKey={React.Component.prototype.checkFunctionProfiles('department.full.path.disabled', [true]) ? 'name' : 'path'}
            onlyNeed="departmentOid"
            onChange={(e, all) => {(copyValue && copyValue.checkedChange && copyValue.checkedChange(field, e, all) || (changeCompanyAndDepart && changeCompanyAndDepart()));}}
            listExtraParams={{ companyOID: companyOIDSetInDep }}
            disabled={!!(field.fieldConstraint && JSON.parse(field.fieldConstraint).valueReadonly)}
            single/>
        );
      case 'currency_code':
        let params = {
          jobId,
          language: 'zh_cn',
          userOId: configureStore.store.getState().login.user.userOID
        };
        return (
          <Selector type={'currency'} params={params} filter={item => item.enable}
                    placeholder={field.promptInfo}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                    showSearch={true}
                    allowClear={true}
                    onChange={(e, all) => {
                      copyValue && copyValue.checkedChange && copyValue.checkedChange(field, e, all)
                    }}
                    disabled={type === 1 ?
                      false:
                      React.Component.prototype.checkFunctionProfiles('invoice.header.multi.currency.allowed', [false])
                    }/>
        );
      case 'remark':
        return <TextArea rows={4} placeholder={field.promptInfo} style={{resize: 'none'}}/>;
      case 'select_cost_center':
        chooserItem = deepFullCopy(chooserData['cost_center_item']);
        chooserItem.url = `${config.baseUrl}/api/my/cost/center/items/${field.dataSource && JSON.parse(field.dataSource || '{}').costCenterOID}`;
        chooserItem.title = field.fieldName;
        // console.log(chooserItem.url)
        if(chooserItem.searchForm && chooserItem.searchForm.length>0){
          chooserItem.searchForm[0].label = messages('components.key815',{arg1:field.fieldName})/*{arg1}代码/名称*/;
        }
        if(chooserItem.columns && chooserItem.columns.length>0){
          chooserItem.columns[0].title = messages('components.key716',{arg1:field.fieldName})/*{arg1}代码*/;
          chooserItem.columns[1].title = messages('components.key717',{arg1:field.fieldName})/*{arg1}名称*/;
        }
        let isSonCostCenter = false;//是否是级联成本中心的子成本中心
        if (field.dataSource && JSON.parse(field.dataSource || '{}').type === 'son') {
          isSonCostCenter = true;
        }
        let fatherCostCenterItemOID = null;//父成本中心的成本中心项oid
        formDetail.customFormFields && formDetail.customFormFields.map(customField => {
          if (customField.messageKey === 'select_cost_center' && customField.dataSource && JSON.parse(customField.dataSource || '{}').type === 'father') {
            fatherCostCenterItemOID = customField.value;
            if ((type === 2 || type === 3) && formValues && customField.fieldOID) {
              fatherCostCenterItemOID = formValues[customField.fieldOID];
            }
          }
        });
        if (isSonCostCenter) {
          chooserItem.url = `${config.baseUrl}/api/cost/center/item/children/${fatherCostCenterItemOID}`;
        }
        let companyValueData = undefined;
        copyValue && copyValue.map(item => {
          if (item.messageKey === 'select_company') {
            let companyValues = this.byMkGetValue(formDetail.customFormFields, 'select_company', formValues);
            companyValueData = item.value ? item.value : companyValues && companyValues[0] && companyValues[0].key
          }
        })
        let companyOIDSet = null;
        let companyValues = this.byMkGetValue(formDetail.customFormFields, 'select_company', formValues);
        let departmentsValues = this.byMkGetValue(formDetail.customFormFields, 'select_department', formValues);
        if (companyValues && companyValues.length > 0 && companyValues[0]) {
          companyOIDSet = companyValues[0];
        } else {
          // 公司控件没有值时，取的应该是岗位所在公司
          companyOIDSet = jobInfo.companyOID;
        }
        // console.log('formDetail', type, companyOIDSet)
        return <Chooser selectorItem={chooserItem}
                        placeholder={field.promptInfo}
                        valueKey="costCenterItemOID"
                        labelKey="name"
                        listExtraParams={{
                          applicantOID: applicantOID || configureStore.store.getState().login.user.userOID,
                          companyOID: type === 3 ? companyValueData : (companyOIDSet && companyOIDSet[0] && companyOIDSet[0].companyOID || (companyOIDSet && companyOIDSet.key)) || companyOIDSet,
                          departmentOID: (departmentsValues && departmentsValues[0]) || jobInfo.departmentOID,
                          formOID: formDetail.formOID
                        }}
                        onlyNeed="costCenterItemOID"
                        onChange={(e, all) => {
                          copyValue && copyValue.checkedChange && copyValue.checkedChange(field, e, all) || onDepartmentChange && onDepartmentChange(field, e, all) || (changeCompanyAndDepart && changeCompanyAndDepart())
                        }}
                        disabled={!!(field.fieldConstraint && JSON.parse(field.fieldConstraint).valueReadonly) || (isSonCostCenter && !fatherCostCenterItemOID) || field.SQ021Edit}
                        single/>;
      case 'select_corporation_entity':
        return <Chooser type="corporation_entity"
                        valueKey="companyReceiptedOID"
                        placeholder={field.promptInfo}
                        labelKey="companyName"
                        onlyNeed="companyReceiptedOID"
                        disabled={field.isReadOnly}
                        single/>;
      case 'select_participant':
        let fieldContent=field.fieldContent?JSON.parse(field.fieldContent):{editable:true};
        chooserItem = deepFullCopy(chooserData['participants']);
        chooserItem.title = `${messages('components.key390'/*选择*/)}${field.fieldName}`;
        chooserItem.key = 'userOID';
        //参与人安全权限校验
        let departmentValues = this.byMkGetValue(formDetail.customFormFields, 'select_department', formValues);
        let departmentOIDSet = '';
        if (departmentValues && departmentValues.length > 0 && departmentValues[0]) {
          departmentOIDSet = `&departmentOID=${departmentValues[0]}`;
        }
        let costCentreValues = this.byMkGetValue(formDetail.customFormFields, 'select_cost_center', formValues);
        let costCentreValue = [];
        let costCentreValuesSet = '';
        if (costCentreValues && costCentreValues.length > 0) {
          costCentreValues.map(item => {
            if (item) {
              costCentreValue.push(`costCentreOID=${item}`)
            }
          })
          if (costCentreValue.length > 0) {
            costCentreValuesSet = '&' + costCentreValue.join('&');
          }
        }
        chooserItem.url += `?proposerOID=${configureStore.store.getState().login.user.userOID}${departmentOIDSet}${costCentreValuesSet}`;
        return <Chooser selectorItem={chooserItem}
                        valueKey="userOID"
                        labelKey="fullName"
                        listExtraParams={{formOID: field.formOID, jobId}}
                        disabled={field.isReadOnly || !fieldContent.editable}
                        onChange={(e, all, from) => {copyValue && copyValue.checkedChange && copyValue.checkedChange(field, e, all, from);}}
                        newline/>;
      case 'select_approver':
        let chooserItem = deepFullCopy(chooserData['user']);
        chooserItem.title = messages('components.key718',{arg1:field.fieldName})/*选择{arg1}*/;
        return <Chooser selectorItem={chooserItem}
                        placeholder={field.promptInfo}
                        valueKey="userOID"
                        listExtraParams={{roleType: 'TENANT'}}
                        labelKey="fullName"
                        onlyNeed="userOID"
                        maxNum={JSON.parse(field.fieldConstraint || '{}').maxApprovalChain || -1}
                        newline/>;
      case 'total_budget':
        if (formDetail.formType != 2005 && formDetail.formType != 2006) {
          return <InputNumber min={0} precision={2} style={{width: '90%', marginRight: 0, float: 'right'}} placeholder={field.promptInfo}/>;
        } else {
          return <InputNumber min={0} precision={propsParams.precision} style={{width: '100%', marginRight: 0, float: 'right'}}  max={9999999999} placeholder={field.promptInfo}/>;
        }
      case 'average_budget':
        return <InputNumber min={0} precision={2} style={{width: '90%', marginRight: 0, float: 'right'}} placeholder={field.promptInfo}/>;
      case 'date':
        return <DatePicker placeholder={field.promptInfo} disabledDate={date => {
          return date && date.valueOf() < new Date(new Date().format('yyyy-MM-dd 00:00:00')).valueOf()
        }} style={{width: '100%'}}/>;
      case 'payee':
        return <NewPayee disabled={field.isReadOnly} placeholder={field.promptInfo}/>;
      case 'contact_bank_account':
        let userOID = configureStore.store.getState().login.user.userOID;
        let containPayee = false;
        let payeeFieldOID = null;
        formDetail.customFormFields.map(item => {
          if (item.messageKey === 'payee') {
            payeeFieldOID = item.fieldOID;
            containPayee = true;
          }
        });
        payeeFieldOID && formValues[payeeFieldOID] && (userOID = formValues[payeeFieldOID].key || userOID);
        return <Chooser type={containPayee ? "bank_card_encryption" : "bank_card"}
                        placeholder={field.promptInfo}
                        valueKey="contactBankAccountOID"
                        labelKey={containPayee ? "originalBankAccountNo" : "bankAccountNo"}
                        onlyNeed="contactBankAccountOID"
                        listExtraParams={{userOID: userOID}}
                        single/>;
      case 'linkage_switch':
        return <NewLinkageSwitch/>;
      case 'venMasterSwitch':
        return <IsVenMaster/>;
      case 'image':
        if (window.ISIE9) {
          return <IeImgUpload attachmentType="INVOICE_IMAGES"
                              fileType={["PNG", 'png', 'JEPG', 'jepg', 'jpg', 'JPG', 'bmp', 'BMP', "jpeg", "JPEG"]}
                              showMaxNum
                              defaultFileList={JSON.parse(field.showValue || '[]')}
                              maxNum={field.fieldConstraint ? JSON.parse(field.fieldConstraint).maxNumber : 9}
                              token={configureStore.store.getState().main.authToken.access_token}/>
        }
        return <ImageUpload attachmentType="INVOICE_IMAGES"
                            fileType={["PNG", 'png', 'JEPG', 'jepg', 'jpg', 'JPG', 'bmp', 'BMP', "jpeg", "JPEG"]}
                            showMaxNum
                            defaultFileList={JSON.parse(field.showValue || '[]')}
                            maxNum={field.fieldConstraint ? JSON.parse(field.fieldConstraint).maxNumber : 9}/>;
      case 'select_box':
        return (
          <Select
            allowClear labelInValue
            placeholder={field.promptInfo}
            mode={JSON.parse(field.fieldConstraint || '{}').type === '1' ? 'multiple' : '-'}
            getPopupContainer={triggerNode => triggerNode.parentNode}
          >
            {JSON.parse(field.fieldContent || '[]').map(item => {
              return <Option key={item.id}>{item.name}</Option>
            })}
          </Select>
        );
      case 'cust_list':
        // console.log('custListParams', custListParams)
        if(constants.CuxRender({formCode, fieldCode: field.fieldCode}).NOTMESSAGEKEY){
          return(
            <Chooser
            disabled={field.readonly}
            selectorItem={selectorItem}
            placeholder={field.promptInfo}
            valueKey="value"
            labelKey="messageKey"
            onlyNeed="value"
            hidePagination={list_key ==='cust_list_overseas' ? true : false}
            listExtraParams={{applicantOID: configureStore.store.getState().login.user.userOID}}
            onChange={(e, all) => {copyValue && copyValue.checkedChange && copyValue.checkedChange(field, e, all);}}
            single
          />
          )
        }
        if(field.fieldCode === "BX"){
          return(
          <Searcher type="proxy_form_admin"
                                    listExtraParams={{
                                      customFormType: 1002,
                                      operationCode:  1,
                                      principalOID: custListParams.principalOID,
                                      proxyOID: custListParams.proxyOID,
                                      type: formCode === 'SQ017' ? 1 : formCode === 'SQ018' ? 2 : undefined
                                    }}
                                    labelKey="formName"
                                    descriptionKey="companyName"
                                    onlyNeed="formName"
                                    isShowSelectAll
                                    showClear={true}
                                    disabled={field.isReadOnly || isCustListSwitch}
                                    onChange={(e, all) => onProxy(field, e, all)}
                          />
          )
        }
        if(field.fieldCode === "JK"){
          return(
          <Searcher type="proxy_form_admin"
                                    listExtraParams={{
                                      customFormType: 3001,
                                      operationCode:  1,
                                      principalOID: custListParams.principalOID,
                                      proxyOID: custListParams.proxyOID,
                                      type: formCode === 'SQ017' ? 1 : formCode === 'SQ018' ? 2 : undefined
                                    }}
                                    labelKey="formName"
                                    descriptionKey="companyName"
                                    onlyNeed="formName"
                                    isShowSelectAll
                                    showClear={true}
                                    disabled={field.isReadOnly || isCustListSwitch}
                                    onChange={(e, all) => onProxy(field, e, all)}
                          />
          )
        }
        if(field.fieldCode === "SQ"){
          return(
          <Searcher type="proxy_form_admin"
                                    listExtraParams={{
                                      customFormType: 1001,
                                      operationCode:  1,
                                      principalOID: custListParams.principalOID,
                                      proxyOID: custListParams.proxyOID,
                                      type: formCode === 'SQ017' ? 1 : formCode === 'SQ018' ? 2 : undefined
                                    }}
                                    labelKey="formName"
                                    descriptionKey="companyName"
                                    onlyNeed="formName"
                                    isShowSelectAll
                                    showClear={true}
                                    disabled={field.isReadOnly || isCustListSwitch}
                                    onChange={(e, all) => onProxy(field, e, all)}
                          />
          )
        }
        if(field.fieldCode === "carIID"){
          return(
          <Searcher type="car_by_user"
                                    listExtraParams={{
                                      employeeID: thirdUserEid
                                    }}
                                    labelKey="carNumber"
                                    descriptionKey="carNumber"
                                    onlyNeed="carNumber"
                                    isShowSelectAll
                                    showClear={true}
                                    single
                                    // disabled={field.isReadOnly || isCustListSwitch}
                                    onChange={(e, all) => onProxy(field, e, all)}
                          />
          )
        }
        //   key: 'value', //报销单和申请单保存时存的都是code，不要再改成OID了～～
        const list_key = (field.fieldCode === 'overseas' || field.fieldCode === 'star' || field.fieldCode === 'TMC') ? 'cust_list_overseas' : (field.fieldName === '支付方式' ? 'multi_cust_list_no_code' : 'multi_cust_list');
        // 麦当劳【出差地】【酒店星级】【TMC预订】控件使用"cust_list_overseas"
        let selectorItem = deepFullCopy(chooserData[list_key]);
        let OID = field.dataSource ? JSON.parse(field.dataSource || '{}').customEnumerationOID : '';
        selectorItem.title = field.fieldName;
        selectorItem.url = `${config.baseUrl}/api/custom/enumerations/${OID}/items/v2`;
        if (field.fieldCode === 'custlist' && formDetail.formCode === 'SQ021') {
          return (
            <Chooser
              selectorItem={selectorItem}
              placeholder={field.promptInfo}
              valueKey="value"
              labelKey="messageKey"
              onlyNeed="value"
              disabled={field.isReadOnly}
              hidePagination={list_key ==='cust_list_overseas' ? true : false}
              listExtraParams={{applicantOID: configureStore.store.getState().login.user.userOID}}
              onChange={(e, all) => {copyValue && copyValue.checkedChange && copyValue.checkedChange(field, e, all);}}
              single
            />)
        }
        return (
          <Chooser
            selectorItem={selectorItem}
            placeholder={field.promptInfo}
            valueKey="value"
            labelKey="messageKey"
            onlyNeed="value"
            hidePagination={list_key ==='cust_list_overseas' ? true : false}
            listExtraParams={{applicantOID: configureStore.store.getState().login.user.userOID}}
            onChange={(e, all) => {copyValue && copyValue.checkedChange && copyValue.checkedChange(field, e, all);}}
            single
          />
        );
      case 'more_cust_list':
        let chooserCustItem = deepFullCopy(chooserData['multi_cust_list']);
        let moreOID = field.dataSource ? JSON.parse(field.dataSource || '{}').customEnumerationOID : '';
        chooserCustItem.title = field.fieldName;
        chooserCustItem.url = `${config.baseUrl}/api/custom/enumerations/${moreOID}/items/v2`;
        return (
          <Chooser
            selectorItem={chooserCustItem}
            placeholder={field.promptInfo}
            valueKey="value"
            labelKey="messageKey"
            listExtraParams={{applicantOID: configureStore.store.getState().login.user.userOID}}
            newline
          />
        );
      case 'number':
        let max = field.fieldConstraint ?
          Math.pow(10, JSON.parse(field.fieldConstraint || '{}').integerMaxLength) - Math.pow(0.1, JSON.parse(field.fieldConstraint || '{}').decimalMaxLength) :
          Infinity;
        //修正整数部分长度
        let fieldCon = field.fieldConstraint ? JSON.parse(field.fieldConstraint) : {decimalMaxLength:2,integerMaxLength:'default'};
        let pre = fieldCon.decimalMaxLength;
        let formatNumber = function (v) {
          let regStr = "^[+-]?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)([eE][+-]?[0-9]+)?$";
          v = v + '';
          let temp = v.match(regStr);
          if(temp){
            v = temp[0];
            let havePoint = v.indexOf('.') >= 0;
            let arr = v.split('.');
            v = arr[0].substr(0,fieldCon.integerMaxLength) + `${havePoint ? '.':''}${arr[1] ? arr[1].substr(0,pre):''}`;
          }
          return v;
        };
        let disabled = false;
        if (field.fieldCode === 'maxnum' || formDetail.formCode === 'SQ021') { // 麦当劳：最大房间数 设置为只读
          disabled = true;
        }

        if (field.fieldCode === 'quota') {
          return <InputNumber style={{width: '100%'}}
                            placeholder={field.promptInfo}
                            disabled={disabled}
                            min={0}
                            formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                            />;
        }

        return <InputNumber style={{width: '100%'}}
                            placeholder={field.promptInfo}
                            disabled={disabled}
                            min={0}
                            formatter={value => `${formatNumber(value)}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                            parser={val => formatNumber(val.replace(/,/g, ''))}
                            precision={pre}/>;
      case 'input':
        //代第三方报销单第三方人员取数
        // if (formDetail.formCode === 'SQ019'  && field.fieldCode === 'thirdUser') {
        //   return <Chooser type="third_user"
        //             valueKey="vnlgnm"
        //             placeholder={field.promptInfo}
        //             labelKey="vnlgnm"
        //             onlyNeed="vnlgnm"
        //             //listExtraParams={{roleType: 'TENANT'}}
        //             single
        //             />;
        // }
        return <Input placeholder={field.promptInfo} disabled={field.isReadOnly}/>;
      case 'text_area':
        return <TextArea rows={4} placeholder={field.promptInfo} style={{resize: 'none'}}/>;
      case 'time':
        return <TimePicker format='HH:mm' allowClear style={{width: '100%'}} placeholder={field.promptInfo}/>;
      case 'attachment':
        if (window.ISIE9) {
          return <IeFileUpload defaultFileList={field.attachmentImages || []}
                               attachmentType="INVOICE_IMAGES"
                               fileSize={10}
                               maxNum={field.fieldConstraint ? JSON.parse(field.fieldConstraint || '{}').maxNumber : 9}
                               showMaxNum
                               placeHolder={field.promptInfo}
                               token={configureStore.store.getState().main.authToken.access_token}/>
        }
        return <FileUpload maxNum={field.fieldConstraint ? JSON.parse(field.fieldConstraint || '{}').maxNumber : 9}
                           showMaxNum
                           placeHolder={field.promptInfo}
                           fileSize={10}
                           defaultFileList={field.attachmentImages || []}
                           attachmentType="INVOICE_IMAGES"/>;
      case 'switch':
        return <Switch
                      onChange={onAgentChange}
                      />;
      case 'destination':
        return <NewDestination placeholder={field.promptInfo} mode={JSON.parse(field.fieldConstraint || '{}').type === '1' ? 'multiple' : ''}/>;
      case 'city':
        return <TravelLocation
          mode={JSON.parse(field.fieldContent || '{}').type === '1' ? 'multiple' : 'single'}
          formCode={formCode}
          placeHolder={field.promptInfo}
          disabled={field.isReadOnly}
        />;
      case 'common.date':
        if (field.fieldCode === 'startDatedaili' || field.fieldCode === 'endDatedaili' || field.fieldCode === 'endDatedali') {
          return <DatePicker
            style={{width: '100%'}}
            placeholder={field.promptInfo}
            disabled={field.isReadOnly}
            disabledDate={date => date && date.valueOf() < moment().subtract(1, 'days').valueOf()}
          />;
        }
        if (field.fieldCode === 'ExpenseYM') {
          return <MonthPicker
            style={{width: '100%'}}
            placeholder={field.promptInfo}
            disabled={field.isReadOnly}
            // disabledDate={date => date && date.valueOf() >= moment().subtract(1, 'days').valueOf()}
          />;
        }
        return <DatePicker style={{width: '100%'}} placeholder={field.promptInfo} disabled={field.isReadOnly}/>;
      case 'select_air_ticket_supplier':
        let supplierParams = {
          category: field.fieldConstraint ? JSON.parse(field.fieldConstraint || '{}').category : ''
        };
        return <Selector type="supplier" params={supplierParams} getPopupContainer={getPopupContainer} placeholder={field.promptInfo}/>;
      case 'dateTime':
        return <DatePicker showTime={{format: 'HH:mm'}} placeholder={field.promptInfo} format="YYYY-MM-DD HH:mm" style={{width: '100%'}}/>;
      case 'select_user':
        // 代第三方报销单的费用确认人不可编辑
        if (formDetail.formCode === 'BX006') {
          return(
            <Chooser
              disabled={true}
              type="user"
              valueKey="userOID"
              placeholder={field.promptInfo}
              labelKey="fullName"
              onlyNeed="userOID"
              listExtraParams={{roleType: 'TENANT'}}
              single={!JSON.parse(field.fieldConstraint || '{}').selectMode}
              newline
            />
          )
        }
        // 礼品申请单的费用确认人
        if (['SQ002', 'SQ021'].includes(formDetail.formCode) && fieldDefaultValue) {
          return <Chooser type="select_user"
                    valueKey="userOID"
                    disabled={field.isReadOnly}
                    placeholder={field.promptInfo}
                    labelKey="fullName"
                    onlyNeed="userOID"
                    listExtraParams={{roleType: 'TENANT', costCenterItemOId: fieldDefaultValue.costCenterItemOID}}
                    single={!JSON.parse(field.fieldConstraint || '{}').selectMode}
                    newline/>;
        }
        if (['SQ017', 'SQ018', 'SQ019'].includes(formDetail.formCode)) {
          if (formDetail.formCode === 'SQ019'  && field.fieldCode === 'thirdUser') {
            console.log('field=============', field)
            return <Chooser type="third_user"
                      valueKey="vnvndr"
                      placeholder={field.promptInfo}
                      labelKey="vnlgnm"
                      onlyNeed="vnvndr"
                      onChange={(e, all, from) => onApproverChange(e, all, from)}
                      //listExtraParams={{roleType: 'TENANT'}}
                      single
                      />;
          } else {
            return <Chooser type={formDetail.formCode === 'SQ019' ? 'car_approval' : 'user'}
                        valueKey="userOID"
                        placeholder={field.promptInfo}
                        labelKey="fullName"
                        onlyNeed="userOID"
                        onChange={(e, all, from) => onApproverChange(e, all, from)}
                        // listExtraParams={{roleType: 'TENANT'}}
                        single={!JSON.parse(field.fieldConstraint || '{}').selectMode}
                        newline/>;
          }
        }
        if (formDetail.formCode === 'SQ007') {

          return <Chooser type='user_card'
                        valueKey="userOID"
                        placeholder={field.promptInfo}
                        labelKey="fullName"
                        onlyNeed="userOID"
                        onChange={(e, all) => onApproverChange(e, all)}
                        listExtraParams={{
                          userOID: additionalDefault,
                          roleType: 'TENANT'
                        }}
                        disabled={!userIsHr}
                        single={!JSON.parse(field.fieldConstraint || '{}').selectMode}
                        newline/>;
        }
        return <Chooser type="user"
                        valueKey="userOID"
                        placeholder={field.promptInfo}
                        labelKey="fullName"
                        onlyNeed="userOID"
                        onChange={onApproverChange}
                        listExtraParams={{roleType: 'TENANT'}}
                        single={!JSON.parse(field.fieldConstraint || '{}').selectMode}
                        newline/>;
      case 'employee_expand':
        if (fieldDefaultValue && fieldDefaultValue.code === 'image') {
          if (window.ISIE9) return <IeImgUpload defaultFileList={fieldDefaultValue.attachmentImages} disabled/>;
          return <ImageUpload defaultFileList={fieldDefaultValue.attachmentImages}
                              attachmentType="INVOICE_IMAGES"
                              disabled/>
        } else if ((field.attachmentImages || []).length) {
          if (window.ISIE9) return <IeImgUpload defaultFileList={field.attachmentImages} disabled/>;
          return <ImageUpload defaultFileList={field.attachmentImages}
                              attachmentType="INVOICE_IMAGES"
                              disabled/>
        }
        else if (field.fieldContent && (JSON.parse(field.fieldContent) || {}).messageKey === 'cust_list') {
          let OID = '';
          if (field.fieldContent && JSON.parse(field.fieldContent)) {
            let fieldItem = JSON.parse(field.fieldContent);
            OID = fieldItem.dataSource ? JSON.parse(fieldItem.dataSource).customEnumerationOID : '';
          }
          let selectorItem = {
            url: `${config.baseUrl}/api/custom/enumerations/${OID}/items/v2?&page=0&size=1000`,
            label: record => record.messageKey,
            key: 'value',
            offlineSearchMode: true,
          };
          return (
            <Selector
              selectorItem={selectorItem}
              disabled
              getPopupContainer={getPopupContainer}
              extraParams={{applicantOID: configureStore.store.getState().login.user.userOID}}
            />
          );
        }
        else {
          return <TextArea autosize disabled style={{resize: 'none'}}/>
        }
      case 'select_special_booking_person':
        return <Chooser type="booker"
                        placeholder={field.promptInfo}
                        valueKey="userOID"
                        labelKey="fullName"
                        onlyNeed="userOID"
                        single/>;
      case 'external_participant_name':
        let external_participant_name_columns = [{
          title: messages('components.key391'/*姓名*/),
          dataIndex: 'name',
          editable: true,
          isRequired: true,
          maxLength: 25
        }];
        let external_participant_name_id = {
          title: messages('components.key392'/*证件号*/),
          dataIndex: 'certificateNo',
          editable: true,
          isRequired: true,
          maxLength: 20,
          onlyCheck: true
        };
        JSON.parse(field.fieldContent || '{}').isContainCard && external_participant_name_columns.push(external_participant_name_id);
        return <AddTableCell columns={external_participant_name_columns}/>;
      case 'out_participant_name':
        let out_participant_name_columns = [{
          title: messages('components.key391'/*姓名*/),
          dataIndex: 'name',
          editable: true,
          isRequired: true,
          maxLength: 25
        }, {
          title: messages('components.key392'/*证件号*/),
          dataIndex: 'certificateNo',
          editable: true,
          isRequired: true,
          maxLength: 20,
          onlyCheck: true
        }];
        return <AddTableCell columns={out_participant_name_columns}/>;
      case 'budget_detail':
        return <ExpenseTypeModal formOID={field.formOID} formDetail={formDetail} copyValue={copyValue} jobInfo={jobInfo}/>;
      case 'writeoff_flag':
        return <Switch/>;
      case 'exp_allocate':
        return <ExpenseAllocateForm copyValue={copyValue}/>;
      case 'start_date':
        return <SelectDateForm copyValue={copyValue} field={field} callFun={(isSet,date)=>copyValue.expectStopDate(isSet,date)}/>;
      case 'end_date':
        return <SelectDateForm copyValue={copyValue} field={field} callFun={(isSet,date)=>copyValue.expectStopDate(isSet,date)}/>;
      case 'range_picker':
        if (field.enableTime) {
          return <RangePicker
                   allowClear={false}
                   getCalendarContainer={triggerNode => triggerNode.parentNode}
                   showTime={{
                     format: 'HH:mm',
                     defaultValue: field.defaultValueTime
                   }}
                   format="YYYY-MM-DD HH:mm"
                   placeholder={[messages('components.key393'/*出发日期*/), messages('components.key394'/*返回日期*/)]}
                   onOpenChange={(e)=>{copyValue && copyValue.checkedOk && copyValue.checkedOk(field,e)}}
                   style={{width: '100%'}}
                   disabled={field.isReadOnly}
                 />;
        } else {
          return <RangePicker
                   allowClear={false}
                   getCalendarContainer={triggerNode => triggerNode.parentNode}
                   format="YYYY-MM-DD"
                   placeholder={[messages('components.key393'/*出发日期*/), messages('components.key394'/*返回日期*/)]}
                   onOpenChange={(e)=>{copyValue && copyValue.checkedOk && copyValue.checkedOk(field,e)}}
                    onChange={(now,origin)=>{
                      if(field.formValueOID=='virtual_range_picker'){
                        field.value=JSON.stringify([new Date(origin[0]).toISOString(),new Date(origin[1]).toISOString()])
                      }
                    }}
                   style={{width: '100%'}}
                   disabled={field.isReadOnly}
                 />;
        }
      case 'venMaster':
        formDetail = formDetail || {};
        let companyOid = null;
        let companyValue = this.byMkGetValue(formDetail.customFormFields, 'select_company', formValues);
        if (companyValue && companyValue.length > 0 && companyValue[0]) {
          companyOid = companyValue[0];
          if (typeof companyOid !== 'string') {
            companyOid = companyOid.key;
          }
        } else {
          companyOid = companyOID || configureStore.store.getState().login.company.companyOID;
        }
        return <NewVenMaster formDetail={formDetail}
                             userOid={configureStore.store.getState().login.user.userOID}
                             companyOid={companyOid} />;
      case 'select_company':
        const unionCompany = JSON.parse(field.fieldConstraint || '{}').unionCompany;
        const notUnionCompany = JSON.parse(field.fieldConstraint || '{}').notUnionCompany;
        let showCode = JSON.parse(field.fieldConstraint || '{}').showCode;
        let isGroup = JSON.parse(field.fieldConstraint || '{}').isGroup;
        let ownCompanyOID = configureStore.store.getState().login.user.companyOID;
        let ownIdentification = function (id) {
          if ((companyOID && companyOID === id) || (!companyOID && ownCompanyOID === id)) {
            return messages('components.key696')/*(我的)*/;
          }
          return '';
        };
        if (unionCompany) { // 工会公司
          return (
            <Chooser
              single
              placeholder={messages('common.please.select')}
              labelKey="name"
              valueKey="companyOID"
              type="auto_audit_add_company"
              listExtraParams={{ isCostCenter: 0 }}
              onChange={(e, all) => { copyValue && copyValue.checkedChange && copyValue.checkedChange(field, e, all) || (onCompanyChange && onCompanyChange(e)) || (changeCompanyAndDepart && changeCompanyAndDepart()) }}
            />
          );
        }

        let selectorItemCompany = {
          url: `${config.baseUrl}/api/refactor/companies/user/setOfBooks?userOID=${applicantOID || configureStore.store.getState().login.user.userOID}&enabled=true&page=0&size=1000&jobId=${jobId}`,
          showSearchLabel: record => showCode ? `${ownIdentification(record.companyOID)}${record.name} - ${record.companyCode}` : `${ownIdentification(record.companyOID)}${record.name}`,
          label: record => showCode ? `${record.name} - ${record.companyCode}` : record.name,
          key: 'companyOID',
          offlineSearchMode: true
        };
        if (isGroup) {
          selectorItemCompany.url = `${config.baseUrl}/api/company/dto/by/useroid/and/company/group?userOID=${applicantOID || configureStore.store.getState().login.user.userOID}&jobId=${jobId}`;
        }
        if (notUnionCompany) { // 非工会公司
          if (formCode === 'BX006') { // 代司机报销，表单信息用的是司机的上司，不是当前登录人，但是提交的时候申请人是当前登录人（秘书）
            selectorItemCompany.url = `${config.baseUrl}/api/refactor/companies/user/setOfBooks2?page=0&size=1000&userOID=${applicantOID}`;
          } else {
            selectorItemCompany.url = `${config.baseUrl}/api/refactor/companies/user/setOfBooks2?page=0&size=1000`;
          }
        }
        return (
          <Selector
            selectorItem={selectorItemCompany}
            disabled={field.isReadOnly}
            placeholder={field.promptInfo}
            onChange={(e, all) => {copyValue && copyValue.checkedChange && copyValue.checkedChange(field, e, all) || (onCompanyChange && onCompanyChange(e)) || (changeCompanyAndDepart && changeCompanyAndDepart())}}
            getPopupContainer={getPopupContainer} showSearch/>
        );
      case 'applicant':
        let selectorItemApplicant = {
          url: `${config.baseUrl}/api/bill/proxy/my/principals/${field.formOID}`,
          label: record => `${record.fullName} - ${record.employeeID}`,
          key: 'userOID',
          dynamicUrl: true
        };
        // 关联申请单会修改url信息
        field.applicationOID && (selectorItemApplicant.url = `${selectorItemApplicant.url}?applicationOID=${field.applicationOID}`);

        return (
          <Selector disabled={true} selectorItem={selectorItemApplicant} onChange={(e, all) => {
            copyValue && copyValue.checkedChange && copyValue.checkedChange(field, e, all)
          }} getPopupContainer={getPopupContainer}/>
        );
      case 'out_participant_num':
        return <InputNumber disabled={field.isReadOnly} max={9999} min={0} precision={0} placeholder={field.promptInfo} style={{width: '100%'}}/>;
      case 'effectiveNum':
        return <InputNumber min={0} precision={0} placeholder={field.promptInfo} style={{width: '100%'}}/>;
      default:
        return <Input placeholder={field.promptInfo}/>
    }
  },
  getKqInitialValue(formCode,field){
    let values = [];
    if (constants.CuxRender({formCode, messageKey: field.messageKey, fieldCode: field.fieldCode}).ALL) {
        values.push({
          messageKey: field.showValue,
          key: field.value,
          value: field.value,
        })
      return values;
    }
  },

  getInitialValue(field) {
    let values = [];
    switch (field.messageKey) {
      case 'public.assembly':
        return field.value;
        // if (field.value === null) return []
        // return JSON.parse(field.value)
      case 'title':
        return field.showValue;
      case 'select_department':
        // return field.value ? [{
        //   [React.Component.prototype.checkFunctionProfiles('department.full.path.disabled', [true]) ? 'name' : 'path']: field.showValue,
        //   departmentOid: field.value
        // }] : undefined;
        // console.log('23412342')
        const {showValue, value} = field;
        return value ? (React.Component.prototype.checkFunctionProfiles('department.full.path.disabled', [true]) ?
          [{name: (showValue||"").split("|").pop(), departmentOid: value}] : [{path: showValue, departmentOid: value}]) : undefined;
      case 'currency_code':
        return field.showValue;
      case 'remark':
        return field.showValue;
      case 'select_cost_center':
        return field.value ? [{name: field.showValue, costCenterItemOID: field.value}] : undefined;
      case 'select_corporation_entity':
        return field.value ? [{companyName: field.showValue, companyReceiptedOID: field.value}] : undefined;
      case 'select_participant':
        let initValue = (field.clearDefault) ? [] : JSON.parse(field.showValue || '[]').map(item => {
          values.push({userOID: item.userOID, fullName: item.fullName, highOff: item.highOff, avatar: item.avatar, gender: item.gender, rankCode: item.rankCode});
        });
        field.clearDefault = false;
        return values;
      case 'select_approver':
        field.showValue && field.showValue.split(',').map((name, index) => {
          values.push({fullName: name, userOID: field.value.split(':')[index]})
        });
        return values;
      case 'total_budget':
        return Number(field.showValue);
      case 'average_budget':
        return Number(field.showValue);
      case 'date':
        return field.showValue ? moment(field.showValue) : undefined;
      case 'payee':
        return field.value ? {key: field.value, label: field.showValue} : undefined;
      case 'contact_bank_account':
        return field.value ? [{
          bankAccountNo: field.showValue && this.isJson(field.showValue) ? JSON.parse(field.showValue).bankAccountNo : field.showValue,
          originalBankAccountNo: bankAccountNoEncryption(field.showValue && this.isJson(field.showValue) ? JSON.parse(field.showValue).bankAccountNo : field.showValue),
          contactBankAccountOID: field.value
        }] : undefined;
      case 'linkage_switch':
        return {
          enabled: field.showValue === 'true',
          fieldContent: field.fieldContent,
          callBackSubmit: false
        };
      case 'venMasterSwitch':
        return {
          enabled: field.showValue === 'true',
          fieldContent: field.fieldContent,
          callBackSubmit: false
        };
      case 'select_box':
        JSON.parse(field.showValue || '[]').map(item => {
          values.push({
            label: item.name,
            key: item.id
          })
        });
        return JSON.parse(field.fieldConstraint || '{}').type === '1' ? values : values[0];
      case 'city':
        let cityValueIsJson = this.isJson(field.showValue);
        if (cityValueIsJson) {
          JSON.parse(field.showValue || '[]').map(item => {
            values.push({
              label: item.city,
              key: item.code
            })
          });
          return JSON.parse(field.fieldContent || '{}').type === '1' ? values : (values[0] ? {adName: values[0].label, adCode: values[0].key} : undefined);
        } else {
          return undefined;
        }
      case 'cust_list':
        if(['BX','SQ','JK'].includes(field.fieldCode)){
          JSON.parse(field.showValue || '[]').map(item => {
            values.push({
              formOID: item.formOID,
              formName: item.formName
            })
          });
          return values ? values : undefined
          // return field.showValue ? [{formOID: field.showValue, formName: field.showValue}] : undefined;
        }
        if (['carIID'].includes(field.fieldCode)) {
          // console.log('field', field)
          JSON.parse(field.showValue || '[]').map(item => {
            values.push({
              id: item.id,
              carNumber: item.carNumber
            })
          });
          return values ? values : undefined
        }
        return field.value ? [{messageKey: field.showValue, value: field.value}] : undefined;
      case 'more_cust_list':
        field.showValue && JSON.parse(field.showValue || '[]').map(custItem => {
          values.push({messageKey: custItem.name, value: custItem.value});
        });
        return values;
      case 'number':
        return Number(field.showValue);
      case 'input':
        // if (field.fieldCode === 'thirdUser'){
        //   if (field.value === null) {
        //     return [];
        //   }
        //   let info = [{ vnvndr: field.value, vnlgnm: field.showValue }]
        //   // console.log('info', info)
        //   return info;
        // }
        // console.log('field', field)
        if (field.fieldName === '默认额度' || field.fieldName === '当前额度' || field.fieldName === '政策规定额度' || field.fieldName === '申请额度') {
          return formatNumber(field.showValue)
        }
        return field.showValue || field.value;
      case 'text_area':
        return field.showValue;
      case 'time':
        //老中控创建的时间是 01:00 格式，所以与需要年份组合转化为moment格式
        return field.showValue ?
          (moment(field.showValue)['_isValid'] ? moment(field.showValue) : moment(new Date(`2000/01/01 ${field.showValue}`))) :
          undefined;
      case 'switch':
        return field.showValue === 'true';
      case 'destination':
        return field.showValue || '';
      case 'common.date':
        return field.showValue ? moment(field.showValue) : undefined;
      case 'select_air_ticket_supplier':
        return field.value ? {label: field.showValue, key: field.value} : undefined;
      case 'dateTime':
        return field.showValue ? moment(field.showValue) : undefined;
      case 'select_user':
        if (field.fieldCode === 'thirdUser'){
          console.log('field', field.showValue.split(',')[0])
          return [{ vnvndr: field.showValue.split(',')[1], vnlgnm: field.showValue.split(',')[0]}]
        } else {
          field.showValue && field.showValue.split(',').map((name, index) => {
            values.push({fullName: name, userOID: field.value.split(':')[index]})
          });
          return field.value ? (JSON.parse(field.fieldConstraint || '{}').selectMode ? values : [values[0]]) : undefined;
        }
      case 'employee_expand':
        if (field && field.fieldContent && (JSON.parse(field.fieldContent) || {}).messageKey === 'cust_list') {
          return field.value ? {label: field.showValue, key: field.value} : undefined;
        }
        return field.showValue;
      case 'select_special_booking_person':
        return field.value ? [{fullName: field.showValue, userOID: field.value}] : undefined;
      case 'external_participant_name':
        return field.showValue ? JSON.parse(field.showValue) : undefined;
      case 'out_participant_name':
        return field.showValue ? JSON.parse(field.showValue) : undefined;
      case 'budget_detail':
        let data = JSON.parse(field.showValue);
        return field.showValue ? (data.amount && data.budgetDetail.length ? data : undefined) : undefined;
      case 'writeoff_flag':
        return field.showValue === 'true';
      case 'exp_allocate':
        return field.showValue ? JSON.parse(field.showValue) : undefined;
      case 'start_date':
        return field.showValue ? moment(field.showValue) : undefined;
      case 'end_date':
        return field.showValue ? moment(field.showValue) : undefined;
      case 'range_picker':
        return field.showValue;
      case 'venMaster':
        return field.value;
      case 'select_company':
        return field.value ? {label: field.showValue, key: field.value} : undefined;
      case 'applicant':
        return field.value ? {label: field.showValue, key: field.value} : undefined;
      case 'image':
        return field.value ? field.value : undefined;
      case 'attachment':
        return field.value ? field.value : undefined;
      case 'out_participant_num':
        return field.showValue;
      case 'effectiveNum':
        return field.showValue;
      default:
        return undefined
    }
  },
  isJson(str) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        } else {
          return false;
        }
      } catch (e) {
        return false;
      }
    } else {
      return false;
    }
  },
  byMkGetValue(customFormFields, mk, formValues = {},type = 'arry') {
    let values
    if (type === 'arry') {
      values = [];
    }
    Array.isArray(customFormFields) && customFormFields.map(item => {
      if (item.messageKey === mk && item.fieldOID) {

        if (type === 'arry') {
          if (formValues[item.fieldOID]) {
            values.push(formValues[item.fieldOID]);
          } else {
            values.push(item.value);
          }
        } else {
          if (formValues[item.fieldOID]) {
            values = formValues[item.fieldOID];
          } else {
            values = item.value;
          }
        }
      }
    })
    return values;
  },
  getDefaultValue(field, fieldDefaultValue, formCode, jobInfo) {
    let user = configureStore.store.getState().login.user;
    let company = configureStore.store.getState().login.company;
    switch (field.messageKey) {
      case 'select_user':
        console.log('fieldDefaultValue', field, fieldDefaultValue)
        if (formCode === 'BX006' ||  formCode === 'SQ002' ||  formCode === 'SQ008') {
          if (fieldDefaultValue.value && fieldDefaultValue.value.length > 0) {
            return [{ userOID: fieldDefaultValue.value, fullName: fieldDefaultValue.showValue }]
          }
        }
        if (formCode === 'SQ007') {
          console.log("1111111122222222", fieldDefaultValue)
          if (field.showValue) {
            return [{ userOID: field.value, fullName: field.showValue }]
          } else if (fieldDefaultValue && fieldDefaultValue.value) {
            return [{ userOID: fieldDefaultValue.value, fullName: fieldDefaultValue.name }]
          }
          // else {
            // return [{ userOID: user.userOID, fullName: user.fullName }]
            // return [{ userOID: '1111', fullName: '1111' }]
          // }
          // return field.showValue ? [{ userOID: field.value, fullName: field.showValue }] : [{ userOID: '1111', fullName: '1111' }]
        }
        if (formCode === 'SQ019') {
          console.log('getDefaultValue', field.showValue)
        }
      case 'public.assembly':
        return field.value ? field.value : '[]';
      /********** 根据接口:/api/custom/form/user/default/values 拿到默认值 Begin ***********/
      case 'select_department':
        if (JSON.parse(field.fieldConstraint || '{}').selectMode && fieldDefaultValue.value) {
          // return [{
          //   [React.Component.prototype.checkFunctionProfiles('department.full.path.disabled', [true]) ? 'name' : 'path']: fieldDefaultValue.name,
          //   departmentOid: fieldDefaultValue.value
          // }]
          const {name, value} = fieldDefaultValue;
          return React.Component.prototype.checkFunctionProfiles('department.full.path.disabled', [true]) ?
            [{name: name.split("|").pop(), departmentOid: value}] : [{path: name, departmentOid: value}];
        }
        return undefined;
      case 'select_approver':
        if (fieldDefaultValue.value) {
          let values = [];
          fieldDefaultValue.value && fieldDefaultValue.value.split(':').map((value, index) => {
            values.push({fullName: fieldDefaultValue.name.split(',')[index], userOID: value})
          });
          return values;
        }
        return undefined;
      case 'remark':
        if (fieldDefaultValue.value) {
          return fieldDefaultValue.value;
        }
        return undefined;
      case 'title':
        if (fieldDefaultValue.value) {
          return fieldDefaultValue.value;
        }
        return undefined;
      case 'cust_list':
        if(constants.CuxRender({formCode, fieldCode: field.fieldCode}).NOTMESSAGEKEY){
          return this.getKqInitialValue(formCode,field);
        }
        if (fieldDefaultValue.value) {
          return [{messageKey: fieldDefaultValue.name, value: fieldDefaultValue.value}];
        }
        return undefined;
      case 'switch':
        return false;
      case 'select_cost_center':
        let initCenterValue = undefined;
        if (fieldDefaultValue.value) {
          initCenterValue = field.clearDefault ? [] : [{
            name: fieldDefaultValue.name,
            costCenterItemOID: fieldDefaultValue.value
          }]
          field.clearDefault = false;
        }
        // if (formCode === 'SQ018') {
        //   initCenterValue = [{
        //     name: jobInfo.departmentPath,
        //     costCenterItemOID: jobInfo.departmentOID
        //   }]
        // }
        return initCenterValue;
      case 'select_corporation_entity':
        if (JSON.parse(field.fieldConstraint || '{}').default && fieldDefaultValue.value) {
          return [{companyName: fieldDefaultValue.name, companyReceiptedOID: fieldDefaultValue.value}]
        }
        return undefined;
      case 'select_company':
        if (!JSON.parse(field.fieldConstraint || '{}').noDefault && fieldDefaultValue.value) {
          let showCode = JSON.parse(field.fieldConstraint || '{}').showCode;
          return {
            key: fieldDefaultValue.value,
            label: showCode ? `${fieldDefaultValue.name} - ${fieldDefaultValue.code}` : fieldDefaultValue.name
          }
        }
        return undefined;
      case 'employee_expand':
        if (fieldDefaultValue.code === 'time') {
          return moment(fieldDefaultValue.value)['_isValid'] ? moment(fieldDefaultValue.value).format('HH:mm:ss') : fieldDefaultValue.value;
        }
        if (fieldDefaultValue.code === 'date') {
          return moment(fieldDefaultValue.value)['_isValid'] ? moment(fieldDefaultValue.value).format('YYYY.MM.DD') : fieldDefaultValue.value;
        }
        if (fieldDefaultValue.code === 'cust_list') {
          return {label: fieldDefaultValue.showValue, key: fieldDefaultValue.value};
        }
        return fieldDefaultValue.value || undefined;
      case 'contact_bank_account':
        if (fieldDefaultValue.value) {
          return [{
            bankAccountNo: fieldDefaultValue.name,
            originalBankAccountNo: bankAccountNoEncryption(fieldDefaultValue.name),
            contactBankAccountOID: fieldDefaultValue.value
          }]
        }
        return undefined;
      /********** 根据接口:/api/custom/form/user/default/values 拿到默认值 End ***********/

      case 'applicant':
        return {label: `${user.fullName} - ${user.employeeID}`, key: user.userOID};
      case 'payee':
        return {label: `${user.employeeID} | ${user.fullName} | ${user.departmentName || messages('components.key395'/*未知*/)}${user.title ? ' | ' + user.title : ''}`, key: user.userOID};
      case 'select_participant':
        let initValue = [];
        if (fieldDefaultValue.value) {
          JSON.parse(fieldDefaultValue.value).map(item => {
            initValue.push({userOID: item.userOID, fullName: item.fullName, gender: item.gender, rankCode: item.rankCode})
          });
          return initValue
        } else {
          // initValue = (field.clearDefault) ? [] : [{userOID: user.userOID, fullName: user.fullName, gender: user.gender, rankCode: user.rankCode}];
          // task#34913 【交付-麦当劳】参与人控件不默认当前用户
          initValue = (formCode === 'MCD3001') ? [] : ((field.clearDefault) ? [] : [{userOID: user.userOID, fullName: user.fullName, gender: user.gender, rankCode: user.rankCode}])
          field.clearDefault = false;
          return initValue;
        }
      case 'linkage_switch':
        return {enabled: false, fieldContent: field.fieldContent, callBackSubmit: false};
      case 'venMasterSwitch':
        return {enabled: false, fieldContent: field.fieldContent, callBackSubmit: false};
      case 'date':
        if (JSON.parse(field.fieldConstraint || '{}').defaultDate) {
          let remindDay = JSON.parse(field.fieldConstraint).defaultDate;
          return moment(new Date().getTime() + remindDay * 24 * 60 * 60 * 1000)
        }
        return undefined;
      case 'currency_code':
        return company.baseCurrency;
      case 'external_participant_name':
        return [];
      case 'out_participant_name':
        return [];
      case 'input':
        // console.log("fieldDefaultValue", fieldDefaultValue)
        if (field.fieldName === '默认额度' || field.fieldName === '当前额度' || field.fieldName === '政策规定额度' || field.fieldName === '申请额度') {
          return fieldDefaultValue.value ? formatNumber(fieldDefaultValue.value) : 0
        }
        return fieldDefaultValue.value || undefined;
      case 'range_picker':
        return fieldDefaultValue.showValue;
      case 'more_cust_list':
        let values = [];
        fieldDefaultValue.showValue && JSON.parse(fieldDefaultValue.showValue || '[]').map(custItem => {
          values.push({messageKey: custItem.name, value: custItem.value});
        });
        return values;
      default:
        return undefined
    }
  },
  formatFormValue(field, value, formCode) {
    if (field.messageKey === 'public.assembly') {
      if (field.isHidden) {
        if (!field.isSwitchOn) {
          value = '[]'
        }
      }
    }
    if (field.messageKey === 'select_box') {
      let tempValue = [];
      try {
        (value || []).map(item => {
          tempValue.push({id: item.key, name: item.label});
        })
      } catch (e) {
        tempValue.push({id: value.key, name: value.label})
      }
      value = tempValue
    }
    if (field.messageKey === 'destination') {
      let tempValue = [];
      try {
        (value || []).map(item => {
          tempValue.push(item);
        })
      } catch (e) {
        tempValue.push(value);
      }
      value = tempValue.join(',');
    }
    if (field.messageKey === 'city') {
      let mode = JSON.parse(field.fieldContent || '{}').type === '1' ? 'multiple' : 'single';
      if (mode === 'single' && value) {
        value = value.adCode;
      }
      if (mode === 'multiple') {
        let tempValue = [];
        try {
          (value || []).map(item => {
            tempValue.push(item.key);
          })
        } catch (e) {
          tempValue.push(value);
        }
        value = tempValue.join(',');
      }
    }
    if (field.messageKey === 'cust_list') {
      if(['BX','JK','SQ'].includes(field.fieldCode)){
        let temp = [];
        (value || []).map(item => {
          temp.push(item);
        });
        value = JSON.stringify(temp);
        field.value =JSON.stringify(temp);
        field.showValue = JSON.stringify(temp);
      }
      if(['carIID'].includes(field.fieldCode)){
        let temp = [];
        (value || []).map(item => {
          temp.push(item);
        });
        value = JSON.stringify(temp);
        field.value =JSON.stringify(temp);
        field.showValue = JSON.stringify(temp);
        // console.log('value', value)
      }
      
    }
    if (field.messageKey === 'more_cust_list') {
      let tempValue = [];
      (value || []).map(item => {
        tempValue.push(item.value);
      });
      value = tempValue.join(',');
    }
    if (field.messageKey === 'select_participant') {
      let valueBuff = [];
      value && value.map(item => {
        valueBuff.push({
          userOID: item.userOID,
          fullName: item.fullName,
          highOff: item.highOff,
          participantOID: item.userOID,
          avatar: item.avatar,
          gender: item.gender,
          rankCode: item.rankCode
        });
      });
      value = valueBuff;
    }
    if (field.messageKey === 'applicant' ||
      field.messageKey === 'select_air_ticket_supplier' ||
      field.messageKey === 'payee') {
      if (typeof value === 'object' && value !== null && value.key) {
        value = value.key
      }
    }
    if (field.messageKey === 'select_company') {
      if (typeof value === 'object' && value !== null && value.key) {
        if (formCode === 'SQ007') {
          value = value.companyOID ? value.companyOID : value.key
        } else {
          value = value.key
        }
      }
    }
    if (field.messageKey === 'employee_expand') {
      if (field.attachmentImages && field.attachmentImages.length) { //个人扩展字段为图片时
        let tempEmployeeExpandValue = [];
        field.attachmentImages.map(item => {
          tempEmployeeExpandValue.push(item.attachmentOID)
        });
        value = tempEmployeeExpandValue.join(',') //保存提交时和老中控统一为 attachmentOID,attachmentOID,... 的格式
      }
      try {
        if (field.fieldContent && (JSON.parse(field.fieldContent) || {}).messageKey === 'cust_list') {
          value = value ? value.key : null
        }
        else {
          if (JSON.parse(value).length) { //个人扩展字段为图片时，用于新建单据时
            value = JSON.parse(value).join(',')
          }
        }
      } catch (e) {}
    }
    if (field.messageKey === 'linkage_switch' || field.messageKey === 'venMasterSwitch') {
      if(value){
        field.fieldContent = value.fieldContent;
        value = JSON.stringify(value.enabled);
      }
    }
    if (field.messageKey === 'select_approver') {
      value = value ? value.join(':') : null;//wjk change value=null 会报错
    }
    if (field.messageKey === 'start_date' && moment.isMoment(value)) {//wjk add 18 04 16
      value = value ? value.utc().format() : "";
    }
    if (field.messageKey === 'end_date' && moment.isMoment(value)) {//wjk add 18 04 16
      value = value ? value.utc().format()  : "";
    }
    if (field.messageKey === 'image' || field.messageKey === 'attachment') {
      value = value || field.showValue
    }
    if (field.messageKey === 'select_user') {
      value = (!value || typeof value === 'string') ? value : value.join(':')
      console.log('value', value)
    }
    if (Array.isArray(value) && value.length === 0) {
      value = null;
    }
    if (field.messageKey === 'number') {
      let fieldCon = field.fieldConstraint ? JSON.parse(field.fieldConstraint) : {decimalMaxLength:2,integerMaxLength:'default'};
      let pre = fieldCon.decimalMaxLength;
      let regStr = "^[+-]?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)([eE][+-]?[0-9]+)?$";
      if (value === null || value === undefined || isNaN(value)) {
        value = '';
      }
      value = value + '';
      let temp = value.match(regStr);
      if(temp){
        value = temp[0];
        let havePoint = value.indexOf('.') >= 0;
        let arr = value.split('.');
        value = arr[0].substr(0,fieldCon.integerMaxLength);//整数位
        //小数位精度不够用0补齐
        if (pre > 0 && !havePoint) {//ep: per 2 value 2 --> 2.00
          value += '.';
          for (let i = 0; i < pre; i++) {
            value += '0';
          }
        } else if (havePoint && arr[1].length !== pre) {//ep: per 2 value 2.1 --> 2.10
          value += `${havePoint ? '.':''}${arr[1] ? arr[1].substr(0,pre):''}`;
          for (let i = 0; i < pre - arr[1].length; i++) {
            value += '0';
          }
        } else {//ep: per 2 value 2.12 --> 2.12
          value += `${havePoint ? '.':''}${arr[1] ? arr[1].substr(0,pre):''}`;
        }
      }
      console.log("value",value)
    }
    if (value === null ||
      typeof value === 'string' ||
      typeof value === 'boolean' ||
      field.messageKey === 'date' ||
      field.messageKey === 'common.date' ||
      field.messageKey === 'time' ||
      field.messageKey === 'dateTime' ||
      field.messageKey === 'start_date' ||
      field.messageKey === 'end_date' ||
      field.messageKey === 'total_budget' ||
      field.messageKey === 'cust_list' ||
      field.messageKey === 'average_budget') {
      field.value = value
    } else {
      field.value = JSON.stringify(value)
    }
    return field;
  },
  instructionsTag(customFormPropertyMap, formCode) {
    if (customFormPropertyMap && customFormPropertyMap['form.description'] && JSON.parse(customFormPropertyMap['form.description'])) {
      let instructions = JSON.parse(customFormPropertyMap['form.description']);
      if (instructions.enable) {
        let title = instructions[configureStore.store.getState().main.language.code] ? instructions[configureStore.store.getState().main.language.code].title : '';
        let content = instructions[configureStore.store.getState().main.language.code] ? instructions[configureStore.store.getState().main.language.code].content : '';
        if (formCode === 'SQ008') return (
          <Alert
            message={title}
            description={content}
            type="warning"
            showIcon
            closable
            style={{ marginBottom: '20px' }}
          />
        )
        return (
          <a className='default-color-font' onClick={() => {
            Modal.info({
              title: (<span style={{whiteSpace: 'normal', wordBreak: 'break-all', wordWrap: 'break-word'}}>{title}</span>),
              content: (<div style={{whiteSpace: 'pre-wrap', maxHeight:200, overflowY:'auto'}} dangerouslySetInnerHTML={{__html: content}}></div>)
            });
          }}>
            <Icon type="info-circle" className='default-color-font' style={{marginRight: 8, position: 'relative'}}/>
            <span style={{whiteSpace: 'normal', wordBreak: 'break-all', wordWrap: 'break-word'}}>{title}</span>
          </a>
        )
      }
    }
  },
  //获取自选审批人的fieldName
  getSignNameForSubmitter(customFormPropertyMap) {
    let signName = messages('components.key376'/*自选审批人*/);
    if (customFormPropertyMap && customFormPropertyMap['countersignNameForSubmitterI18n'] && JSON.parse(customFormPropertyMap['countersignNameForSubmitterI18n'])) {
      let signNameList = JSON.parse(customFormPropertyMap['countersignNameForSubmitterI18n']);
      let currentLanguageCode = configureStore.store.getState().main.language.code;
      signNameList && signNameList.map(name => {
        if (name.language === currentLanguageCode && name.value) {
          signName = name.value;//有值的时候再覆盖
        }
      });
    }
    return signName;
  },
  messageKeys: [
    'applicant',                      //申请人
    'writeoff_flag',                  //是否核销借款
    'total_budget',                   //借款金额
    'title',                          //事由
    'start_date',
    'remark',                         //备注
    'text_area',                      //多行输入框
    'select_participant',             //参与人员
    'end_date',
    'currency_code',                  //币种
    'budget_detail',                  //添加预算类型及金额
    'average_budget',
    'select_cost_center',             //成本中心
    'select_department',              //部门
    'destination',                    //地点
    'out_participant_num',            //外部参与人数
    'select_special_booking_person',  //订票专员
    'select_approver',                //审批人
    'select_air_ticket_supplier',     //供应商
    'select_corporation_entity',      //法人实体
    'linkage_switch',                 //联动开关
    'cust_list',                      //自定义列表
    'more_cust_list',                 //多选自定义值列表
    'select_user',                    //选人
    'select_box',                     //选择框
    'attachment',                     //附件
    'time',                           //时间
    'contact_bank_account',           //银行卡号
    'date',                           //预计还款日期
    'out_participant_name',           //外部参与人员姓名（老单据），和external_participant_name（新单据）作用一样
    'number',                         //数字
    'substitution_invoice',           //替票，费用里的字段，申请单和报销单没有该messageKey
    'exp_allocate',                   //费用分摊
    'venMaster',                      //收款单位/个人
    'venMasterSwitch',                //组合控件，供应商支付控件
    'employee_expand',                //个人信息扩展字段
    'select_company',                 //公司
    'input',                          //单行输入框
    'LONG',
    'dateTime',                       //日期时间
    'common.date',                    //日期
    'Destination',
    'switch',                         //普通开关
    'payee',                          //收款方
    'image',                          //图片
    'external_participant_name',      //外部乘机人
    'effectiveNum',                   //有效人数
  ],
}
